<template>
	<div class="addMedication">
		<span class="tittle">康恒医院医生开药</span>
		<el-form ref="form" label-width="80px" class="addForm">
			<h3>选择患者</h3>
			<hr />
			<el-form-item label="姓名" prop="doctor">
				<el-select style="width: 130px" placeholder="必填" v-model="form.name" @change="handleSelectChange">
					<el-option v-for="item in formlist" :key="item.id"
						:label="item.id + ' ' + item.name + ' ' + item.phone" :value="item.id">
					</el-option>
				</el-select>
			</el-form-item>
			<h3>患者信息</h3>
			<hr />
			<el-form-item label="编号">
				{{ form.number }}
			</el-form-item>
			<el-form-item label="性别">
				{{ form.sex }}
			</el-form-item>
			<el-form-item label="年龄">
				{{ form.age }}
			</el-form-item>
			<el-form-item label="联系方式">
				{{ form.phone }}
			</el-form-item>
		</el-form>
		<hr />
		<div style="margin: 30px 100px;">
			当前选择的药:
			<el-select style="width: 50px" v-model="drugsListAllIndex" @change="handleDrug">
				<el-option v-for="item in drugsListAllValue" :key="item.id"
					:label="item.drugname+' ： '+item.medicineNumber " :value="item.id">
				</el-option>
			</el-select>
		</div>
		<div style="margin: 10px 180px; position: absolute; left: 25%; top: 540px;">
			中西药:
			<el-select style="width: 50px" v-model="drugShowKey" @change="handleSelectDrug">
				<el-option v-for="item in drugShow" :key="item.key" :label="item.value" :value="item.key">
				</el-option>
			</el-select>
		</div>
		<div style="margin: 10px 180px; position: absolute; left: 45%; top: 540px;">
			<el-input style="width: 200px;" class="filter-item" placeholder="药品姓名" v-model="searchName"></el-input>
			<el-button type="primary" @click="handelSearch">搜索</el-button>
			<el-button type="primary" @click="getAll">显示全部</el-button>
		</div>
		<div style="margin: 10px 180px; position: absolute; left: 75%; top: 540px;">
			<el-button type="primary" @click="submit">提交</el-button>
		</div>
		<el-table :data="drugsList" style="width: 90%; margin: 0 auto;" height="400">
			<el-table-column prop="type" label="药品分类" width="100">
			</el-table-column>
			<el-table-column prop="drugname" label="药品名称" width="200">
			</el-table-column>
			<el-table-column prop="quantity" label="库存（件/盒）" width="150">
			</el-table-column>
			<el-table-column prop="price" label="价格（元）" width="120">
			</el-table-column>
			<el-table-column label="备注" width="340">
				<template slot-scope="scope">
					<el-input style="width: 300px;" class="filter-item" placeholder="备注"
						v-model="scope.row.remark"></el-input>
				</template>
			</el-table-column>
			<el-table-column prop="medicinePrice" label="小计（元）" width="115">
			</el-table-column>
			<el-table-column label="用量" width="250">
				<template slot-scope="scope">
					<div style="margin: 10px 0;">
						{{scope.row.drugname}}
						<el-input-number v-model="scope.row.medicineNumber" @change="handleChange(scope.row, scope.$index)"
							:min="0" :max="scope.row.quantity"></el-input-number>
					</div>
				</template>
			</el-table-column>
		</el-table>
	</div>
</template>

<script type="text/ecmascript-6">
	export default {
		data() {
			return {
				//患者信息
				formlist: [],
				form: [],
				//处方信息
				drugShowKey: '全部',
				drugShow: [{
						key: '全部',
						value: '全部'
					},
					{
						key: '中药',
						value: '中药'
					},
					{
						key: '西药',
						value: '西药'
					}
				],
				drugs: [], //中药
				drugsW: [], //西药
				//患者处方信息
				drugsList: [],
				drugsListAll: [],
				drugsListAllValue: [],
				drugsListAllIndex: '点击查看',
				searchName: '' //搜索

			};
		},
		methods: {
			handleSelectChange(selectedId) {//选择患者时
				const form = this.formlist.find(nurse => nurse.id === selectedId);
				if (form) {
					this.form = {
						...form
					};
				}
			},
			init() {
				//病患信息
				let that = this;
				let apilogin = "http://localhost:8088/getAllPatientList";
				this.$http.get(apilogin).then((response) => {
					that.formlist = response.body.data.Patient;
				}, response => {
					this.$message({
						message: '数据请求失败',
						type: 'error'
					});
				});

				//中药信息
				apilogin = "http://localhost:8088/getDrugsByType";
				this.$http.get(apilogin).then((response) => {
					that.drugs = response.body.data.list;
					this.mergeDrugs(); // 合并药物列表
				}, response => {
					this.$message({
						message: '数据请求失败',
						type: 'error'
					});
				});

				//西药信息
				apilogin = "http://localhost:8088/getDrugsByTypeW";
				this.$http.get(apilogin).then((response) => {
					that.drugsW = response.body.data.list;
					this.mergeDrugs(); // 合并药物列表
				}, response => {
					this.$message({
						message: '数据请求失败',
						type: 'error'
					});
				});
			},
			// 新增方法用于合并药物列表并添加默认值
			mergeDrugs() {
				this.drugs = this.drugs.map((drug, index) => ({
					...drug,
					medicineNumber: 0, // 默认开药数量
					medicinePrice: 0, // 小计
					Index: index // 添加下标
				}));

				this.drugsW = this.drugsW.map((drug, index) => ({
					...drug,
					medicineNumber: 0, // 默认开药数量
					medicinePrice: 0, // 小计
					Index: index // 添加下标
				}));

				this.drugsList = [...this.drugs, ...this.drugsW];
				this.drugsListAll = [...this.drugsList];
			},
			//用量变化时
			handleChange(row) {
				this.$nextTick(() => {
					row.medicinePrice = parseFloat((row.medicineNumber * row.price).toFixed(2));
					// 使用 row.Index
					this.drugsListAll[row.Index].medicineNumber = row.medicineNumber;
					// 使用 row.Index
					this.drugsListAll[row.Index].medicinePrice = row.medicinePrice;

					const entityList = this.drugsListAll.filter(drug => drug.medicineNumber > 0).map(drug => ({
						...drug
					}));
					this.drugsListAllValue = entityList;
				});
			},
			//选择中西药品
			handleSelectDrug(obj) {
				this.$nextTick(() => {
					if (obj == "中药") {
						this.drugsList = [...this.drugs];
					} else if (obj == "西药") {
						this.drugsList = [...this.drugsW];
					} else {
						this.drugsList = [...this.drugs, ...this.drugsW];
					}
				});
			},
			handelSearch() {
				this.drugShowKey = '全部';
				let that = this;
				//根具物品名字搜索
				let apilogin = "http://localhost:8088/getDrugsByDrugNameLike/" + this.searchName;
				this.$http.get(apilogin).then((response) => {
					for (var i = 0; i < response.body.data.list.length; i++) {
						for (var j = 0; j < that.drugsList.length; j++) {
							if (response.body.data.list[i].id == that.drugsList[j].id) {
								response.body.data.list[i].Index = that.drugsList[j].Index;
							}
						}
					}
					that.drugsList = response.body.data.list.map(drug => ({
						...drug,
						medicineNumber: 0, // 默认开药数量
						medicinePrice: 0 // 小计
					}));
				}, response => {
					this.$message({
						message: '数据请求失败',
						type: 'error'
					});
				});
			},
			//查看所有
			getAll() {
				this.drugsList = [...this.drugsListAll];
				this.searchName = '';
			},
			submit() {
				if (this.form.number == null || this.form.number == '') {
					this.$message({
						message: '请选择患者!',
						type: 'warning'
					});
					return;
				}
				// 收集需要提交的药物信息
				const entityList = this.drugsList.filter(drug => drug.medicineNumber > 0).map(drug => ({
					patientNumber: this.form.number,
					drugName: drug.drugname,
					quantity: drug.medicineNumber,
					remark: drug.remark,
					type: drug.type,
					price: drug.medicinePrice
				}));

				if (entityList.length === 0) {
					this.$message({
						message: '请至少选择一种药物',
						type: 'warning'
					});
					return;
				}

				// 发送请求到后台
				this.$http.post("http://localhost:8088/insertPrescriptions", entityList, {
					headers: {
						'Content-Type': 'application/json'
					}
				}).then((response) => {
					this.$message({
						message: '提交成功',
						type: 'success'
					});
					//查看开药是否大于0
					const entityListId = this.drugsList.filter(drug => drug.medicineNumber > 0).map(drug => ({
						id: drug.id,
						drugName: drug.drugname,
						quantity: drug.medicineNumber
					}));
					//开药成功的话就减少库存
					for (var i = 0; i < entityListId.length; i++) {
						this.$http.post("http://localhost:8088/updateDrugsQuantity", entityListId[i]).then((
							response) => {
							console.log('减少库存成功');
						})
					}

					// 初始化表单和药物列表
					this.form = [];
					this.drugsListAllValue = [];
					this.init();
				}).catch((response) => {
					this.$message({
						message: '提交失败',
						type: 'error'
					});
				});
			},
			
			handleDrug() {
				this.drugsListAllIndex = '点击查看'
			}
		},
		mounted() { //初始化
			this.init();
		}
	};
</script>

<style>
	.addMedication .el-input {
		width: 200px;
	}

	.addMedication .tittle {
		display: block;
		text-align: center;
		font-size: 24px;
		line-height: 80px;
	}

	.addMedication .addForm {
		width: 470px;
		margin: auto;
	}

	.addMedication .addForm .buttonAdd {
		text-align: center;
	}

	.el-input-number {
		width: 200px;
	}
</style>